import { useEffect, useState, useRef, MutableRefObject } from 'react';
import { viewUtils } from '@/utils/arcgis/index';
import { jsapi } from '@/utils/arcgis';


export type BasicTarget<T = HTMLElement> =
  | (() => T | null)
  | T
  | null
  | MutableRefObject<T | null | undefined>;
type TargetElement = HTMLElement | Document | Window;

export function getTargetElement(
  target?: BasicTarget<TargetElement>,
  defaultElement?: TargetElement,
): TargetElement | undefined | null {
  if (!target) {
    return defaultElement;
  }

  let targetElement: TargetElement | undefined | null;

  if (typeof target === 'function') {
    targetElement = target();
  } else if ('current' in target) {
    targetElement = target.current;
  } else {
    targetElement = target;
  }

  return targetElement;
}

/**
 * slice hook - 剖切逻辑抽成hook
 *
 * @param target - 指定剖切挂载的的react ref 或者 div元素
 * @returns [isLoading] - 剖切功能加载状态
 
 * @date 2020-08-03
 * @beta
 */
function useSlice(target: BasicTarget): [boolean] {
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const vmRef = useRef<any>();

  useEffect(() => {
    if (!target) return;
    init();
    return () => {
      vmRef.current && vmRef.current!.destroy();
    };
  }, [target]);

  async function init() {
    const view = await viewUtils.isViewReady();
    const [Slice] = await jsapi.load(['esri/widgets/Slice']);
    const targetElement = getTargetElement(target);
    if (!targetElement) {
      return
    }
    vmRef.current = new Slice({
      view: view,
      container: targetElement,
    });

    setIsLoading(false);
  }

  return [isLoading];
}

export default useSlice;
